package tungsten.base.event;

import tungsten.base.thread.ThreadPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* 这个事件侦听器，听到的事件会直接放到线程池里执行，他不保证Event是按队列的方式执行的
 * Created by lv on 16-6-26.
 */
public class MultiEventDispatcher implements IEventDispatcher {
    private Map<Integer,IEventHandler> handlerMap = new ConcurrentHashMap<>();
    @Override
    public void onEvent(Event event)
    {
        ThreadPool.submit(EventBus.EVENT_THREAD, () -> {
            try {
                handlerMap.get(event.getType()).execute(event);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void addEventListener(int type, IEventHandler handler)
    {
        EventBus.addEventListener(type,this);
        handlerMap.put(type,handler);
    }

    @Override
    public void removeEventListener(int type)
    {
        EventBus.removeEventListener(type,this);
        handlerMap.remove(type);
    }

    @Override
    public void dispatchEvent(Event event) {
        EventBus.dispatchEvent(event);
    }
}
